

var z = z || {};

(function () {
//z.cdn = 'http://cdn.i.com';
z._init = function () {
    var na = navigator, ua = na.userAgent;
    z.isOpera = window.opera && opera.buildNumber;

    z.isWebKit = /WebKit/.test(ua);

    z.isIE = !z.isWebKit && !z.isOpera && (/MSIE/gi).test(ua) && (/Explorer/gi).test(na.appName);

    z.isIE6 = z.isIE && /MSIE [56]/.test(ua);

    z.isGecko = !z.isWebKit && /Gecko/.test(ua);

    z.isMac = ua.indexOf('Mac') != -1;

    z.isAir = /adobeair/i.test(ua);

    z.isIDevice = /(iPad|iPhone)/.test(ua);
};

z.extend = function(target, options) {

    if ( typeof target !== "object") {
        target = {};
    }
    var name, src, copy;
    for ( name in options ) {
        //src = target[ name ];
        copy = options[ name ];
        
        if (copy !== undefined) {
            target[name] = copy;
        }
    }

    return target;
};
z.parseJSON = function( data ) {
    if ( typeof data !== "string" || !data ) {
        return null;
    }
    data = z.trim( data );

    // Attempt to parse using the native JSON parser first
    if ( window.JSON && window.JSON.parse ) {
        return window.JSON.parse( data );
    }
    var rvalidchars = /^[\],:{}\s]*$/;
    var rvalidescape = /\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g;
    var rvalidtokens = /"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g;
    var rvalidbraces = /(?:^|:|,)(?:\s*\[)+/g;
    
    // Make sure the incoming data is actual JSON
    // Logic borrowed from http://json.org/json2.js
    if ( rvalidchars.test( data.replace( rvalidescape, "@" )
        .replace( rvalidtokens, "]" )
        .replace( rvalidbraces, "")) ) {

        return (new Function( "return " + data ))();

    }
    jQuery.error( "Invalid JSON: " + data );
};
z.html_strip = function (str, length) {
    var str = str.replace(/<[^><]*>/ig, '').replace('/\s+/i', ' ');
    var length = parseInt(length);
    if (length > 0) {
        var pos = str.indexOf(' ', length);
        if (pos > 0) {
            str = str.substr(0, pos);
        }
    }
    return str;
};
z.query_encode = function (str) {
    var str = str.replace(/\s+/ig, '-').toLowerCase();
    return escape(str);
};
z.highlight = function (bodyText, searchTerm, highlightStartTag, highlightEndTag) 
{
  // the highlightStartTag and highlightEndTag parameters are optional
  if ((!highlightStartTag) || (!highlightEndTag)) {
    highlightStartTag = "<font style='color:blue; background-color:yellow;'>";
    highlightEndTag = "</font>";
  }
  var newText = "";
  var i = -1;
  var lcSearchTerm = searchTerm.toLowerCase();
  var lcBodyText = bodyText.toLowerCase();
    
  while (bodyText.length > 0) {
    i = lcBodyText.indexOf(lcSearchTerm, i+1);
    if (i < 0) {
      newText += bodyText;
      bodyText = "";
    } else {
      // skip anything inside an HTML tag
      if (bodyText.lastIndexOf(">", i) >= bodyText.lastIndexOf("<", i)) {
        // skip anything inside a <script> block
        if (lcBodyText.lastIndexOf("/script>", i) >= lcBodyText.lastIndexOf("<script", i)) {
          newText += bodyText.substring(0, i) + highlightStartTag + bodyText.substr(i, searchTerm.length) + highlightEndTag;
          bodyText = bodyText.substr(i + searchTerm.length);
          lcBodyText = bodyText.toLowerCase();
          i = -1;
        }
      }
    }
  }
  
  return newText;
};
z.s = function (id) {
    return document.getElementById(id);
};
z.clean_url = function (str) {
    var str = str.replace(/[^a-z0-9]+/ig, '-').toLowerCase();
    return z.trim(str, '-');
};
z.clean_keyword = function (str) {
    str = str.replace(/[^a-z0-9 ]+/ig, '').toLowerCase();
    return str.replace(/ +/, ' ').toLowerCase();
};
z.event = {
    addListener: function (target, name, fct) {
        if ( ! target.events) {
            target.events = {};
        }
        target.events[name] = fct;
    }
    //google.maps.event.addListener(marker, 'click', function() {
};
z.addEvent = function (obj, evType, fn){
	if(obj.addEventListener)
	    obj.addEventListener(evType, fn, true);
	else if(obj.attachEvent)
	    obj.attachEvent("on"+evType, fn);
};
z.removeEvent = function (obj, type, fn){
	if(obj.detachEvent){
		obj.detachEvent('on'+type, fn);
	}else{
		obj.removeEventListener(type, fn, false);
	}
};
z.cancelEvent = function (e) {
    if(e&&e.preventDefault){
        e.preventDefault();
        e.stopPropagation();
    }else{
        event.cancelBubble=true;
        event.returnValue=false;
    }
    return false;
};
z.show_pop = function (html, target) {
    var pop = z.s('z_pop');
    if ( ! pop) {
        pop = document.createElement('div');
        pop.className = 'box';
        pop.id = 'z_pop';
        
        var close_bt = document.createElement('a');
        close_bt.href = 'javascript:;';
        close_bt.innerHTML = 'close';
        close_bt.onclick = function () {
            this.parentNode.style.display = 'none';
        };
        pop.appendChild(close_bt);
        
        var body = document.createElement('div');
        pop.appendChild(body);
        pop.body = body;
        document.body.appendChild(pop);
    }
    pop.style.display = 'block';
    pop.body.innerHTML = html;
    if (target) {
        var pos = z.getAbsOffset(target);
        pop.style.top = (pos.top - 10) + 'px';
        pop.style.left = (pos.left + 20) + 'px';
    }
};
z.getMousePos = function (e, target) {
    var pos = {};
    var offsetLeft = 0;
    var offsetTop = 0;
    if (target && target.nodeType) {
        // offsetLeft = (target.offsetLeft) ? target.offsetLeft : 0;
        // offsetTop = (target.offsetTop) ? target.offsetTop : 0;
        var obj = target;
        while (obj) {
            offsetLeft += obj.offsetLeft;
            offsetTop += obj.offsetTop;
            obj = obj.offsetParent;
        }
    }
    //evt.clientX + (document.documentElement.scrollLeft ? document.documentElement.scrollLeft : document.body.scrollLeft)
    pos.x = parseInt((e && e.pageX)?e.pageX:event.clientX + (document.documentElement.scrollLeft ? document.documentElement.scrollLeft : document.body.scrollLeft)) - offsetLeft;
    pos.y = parseInt((e && e.pageY)?e.pageY:event.clientY + (document.documentElement.scrollTop ? document.documentElement.scrollTop : document.body.scrollTop)) - offsetTop;
    return pos;
};
z.getAbsOffset = function (target) {
    var offsetLeft = 0;
    var offsetTop = 0;

    if (target && target.nodeType) {
        // offsetLeft = (target.offsetLeft) ? target.offsetLeft : 0;
        // offsetTop = (target.offsetTop) ? target.offsetTop : 0;
        var obj = target;
        while (obj) {
            offsetLeft += obj.offsetLeft;
            offsetTop += obj.offsetTop;
            obj = obj.offsetParent;
        }
    }
    return {
        left: offsetLeft,
        top: offsetTop
    };
};
z.getScrollXY = function() {
  var scrOfX = 0, scrOfY = 0;
  if( typeof( window.pageYOffset ) == 'number' ) {
    //Netscape compliant
    scrOfY = window.pageYOffset;
    scrOfX = window.pageXOffset;
  } else if( document.body && ( document.body.scrollLeft || document.body.scrollTop ) ) {
    //DOM compliant
    scrOfY = document.body.scrollTop;
    scrOfX = document.body.scrollLeft;
  } else if( document.documentElement && ( document.documentElement.scrollLeft || document.documentElement.scrollTop ) ) {
    //IE6 standards compliant mode
    scrOfY = document.documentElement.scrollTop;
    scrOfX = document.documentElement.scrollLeft;
  }
  return {x: scrOfX, y: scrOfY };
};

z.browzer = function () {
    if ( ! z._browzer) {
        var ua = navigator.userAgent.toLowerCase();
        
        var rwebkit = /(webkit)[ \/]([\w.]+)/,
            ropera = /(opera)(?:.*version)?[ \/]([\w.]+)/,
            rmsie = /(msie) ([\w.]+)/,
            rmozilla = /(mozilla)(?:.*? rv:([\w.]+))?/;

		var match = rwebkit.exec( ua ) ||
			ropera.exec( ua ) ||
			rmsie.exec( ua ) ||
			ua.indexOf("compatible") < 0 && rmozilla.exec( ua ) ||
			[];

		z._browzer = { browser: match[1] || "", version: match[2] || "0" };
    }
    return z._browzer;    
};

 
z.ltrim = function (str, chars) {
	chars = chars || "\\s";
	return str.replace(new RegExp("^[" + chars + "]+", "g"), "");
};
 
z.rtrim = function (str, chars) {
	chars = chars || "\\s";
	return str.replace(new RegExp("[" + chars + "]+$", "g"), "");
};

z.trim = function (str, chars) {
	return z.ltrim(z.rtrim(str, chars), chars);
};


z.time = new Date();
z.interval = 100;
z.timespan = 0;
z.setDateTime = function (t) {
    z.time = new Date(t);
};
z.getTime = function (offset) {
    var t = z.time;
    //var s = t.getFullYear() + '-' + (t.getMonth() + 1) + '-' + t.getDate() + ' ' + t.getHours() + ':' + t.getMinutes() + ':' + t.getSeconds();
    //return s;
    if (offset) 
        t += offset;
    return z.parseTime(t);
};
z.getShortTime = function () {
    var t = z.time;
    return z.parseShortTime(t);
};
z.parseShortTime = function (t) {
    var hours = t.getHours();
    var minutes = t.getMinutes();
    var seconds = t.getSeconds();
    
    hours = z._pd(hours);
    minutes = z._pd(minutes);
    seconds = z._pd(seconds);
    var s = hours + ':' + minutes + ':' + seconds;
    return s;
};
z.parseTime = function (t) {
    var fullYear = t.getFullYear();
    var month = t.getMonth() + 1;
    var date = t.getDate();
    var hours = t.getHours();
    var minutes = t.getMinutes();
    var seconds = t.getSeconds();
    
    month = z._pd(month);
    date = z._pd(date);
    hours = z._pd(hours);
    minutes = z._pd(minutes);
    seconds = z._pd(seconds);
    var s = fullYear + '-' + month + '-' + date + ' ' + hours + ':' + minutes + ':' + seconds;
    //var s = t.getFullYear() + '-' + (t.getMonth() + 1) + '-' + t.getDate() + ' ' + t.getHours() + ':' + t.getMinutes() + ':' + t.getSeconds();
    return s;
};
z._pd = function (d) {
    if (d < 10) d = '0' + d;
    return d;
};
z.setInterval = function (val) {
    z.interval = val;
};
z.loop = function() {
    var interval = z.interval;
    z.time.setTime(z.time.getTime() + interval);
    z.timespan += interval;
    var timespan = z.timespan;
    if (z.events) {
        if (z.events['200ms'] && timespan % 200 == 0) {
            z.events['200ms'].call(z);
        }
        
        if (z.events['1s'] && timespan % 1000 == 0) {
            z.events['1s'].call(z);
        }
    }
    /*if (timespan % 5000 == 0) {
        z.events['5s'].call(z);
    }*/
    
};
z.hasClass = function (target, classValue) {
	var pattern = new RegExp("(^| )" + classValue + "( |$)");
	if (target.className.match(pattern)) {
		return true;
	} else {
		return false;
	}
};
z.addClass = function (target, classValue) {
	if ( ! z.hasClass(target, classValue)) {
		if (target.className == '') {
			target.className = classValue;
		} else {
			target.className += " " + classValue;
		}
	}
};
z.removeClass = function (target, classValue) {
	var removedClass = target.className;
	var pattern = new RegExp("(^| )" + classValue + "( |$)");
	removedClass = removedClass.replace(pattern, "$1");
	removedClass = removedClass.replace(/ $/, "");
	target.className = removedClass;
	return true;
};

z.uploadImg = function (path, caption, src, callback) {
	var uploadForm = z.s('upload_img_form');
	if ( ! uploadForm) {
		uploadForm = document.createElement('form');
		uploadForm.setAttribute("target","ajax-temp-img-upload");
		uploadForm.setAttribute("action","?m=media&a=upload&type=img");
		uploadForm.setAttribute("method","post");
		uploadForm.setAttribute("enctype","multipart/form-data");
		uploadForm.setAttribute("encoding","multipart/form-data");
		//uploadForm.setAttribute("style","position: absolute; top: 50px; left: 100px; background:#fff; border: 1px solid #E8E8E8; width: 500px;");
		uploadForm.id = 'upload_img_form';
		//<input id="file" type="file" name="file">
		
		var iframe = document.createElement("iframe");
		iframe.setAttribute("id","ajax-temp-img-upload");
		iframe.setAttribute("name","ajax-temp-img-upload");
		iframe.setAttribute("width","0");
		iframe.setAttribute("height","0");
		iframe.setAttribute("border","0");
		iframe.setAttribute("style","width: 0; height: 0; border: none;");
		
		var img_container = document.createElement('div');
		img_container.id = 'upload_img_wrap';
		
		var img = document.createElement('img');
		img.id = 'upload_img';
		//http://cdn.i.com/sys/img/icon/big-blueprint.png
		img.src = z.cdn + '/sys/img/icon/big-blueprint.png';
		img_container.appendChild(img);
		
		z.addEvent(iframe,"load", function () {
			//img_container.innerHTML = document.body.innerHTML;
			//var cross = "javascript: if (document.getElementById('result')) window.parent.z.s('upload_img').src = document.getElementById('result').value; void(0);";
			//z.s('ajax-temp-img-upload').src = cross;
			var iframe = z.s('ajax-temp-img-upload');
			var iframeDoc = iframe.contentDocument || iframe.contentWindow.document;
			var result = iframeDoc.getElementById('result');
			if (result) {
				var src = result.value;
				var obj = new Image();
				var elem = z.s('upload_img');
				obj.src = z.cdn + '/' + src;
				elem.osrc = src;
				if (obj.complete) {
					if (obj.width > 450) {
						elem.width = '450';
					}
					elem.src = obj.src;
					
				}
				obj.onload = function () {
					if (this.width > 450) {
						elem.width = '450';
					}
					elem.src = this.src;
				};
				//z.s('upload_img').src = src;
			}
		});
		
		var input_caption = document.createElement('input');
		input_caption.setAttribute("type", "text");
		input_caption.setAttribute("name", "img_caption");
		input_caption.id = 'img_input_file';
		input_caption.value = caption;
		input_caption.className = 'text';
		
		var input_path = document.createElement('input');
		input_path.type = 'hidden';
		input_path.name = 'path';
		input_path.value = path;

		var input_file = document.createElement('input');
		input_file.setAttribute("type", "file");
		input_file.setAttribute("name", "img_input_file");
		input_file.id = 'img_input_file';
		input_file.className = 'file';
		input_file.onchange = function () {
			input_file.form.submit();
		};
		
	
		var aOK = document.createElement('a');
		aOK.href = 'javascript:;';
		aOK.innerHTML = 'OK ';
		aOK.onclick = function () {
			var obj = {};
			var elem = z.s('upload_img');
			obj.src = elem.src;
			obj.osrc = elem.osrc;
			callback.call(obj);
			uploadForm.style.display = 'none';
		};
		
		var aCancel = document.createElement('a');
		aCancel.href = 'javascript:;';
		aCancel.innerHTML = 'Cancel';
		aCancel.onclick = function () {
			uploadForm.style.display = 'none';
		};
		
		
		
		uploadForm.appendChild(input_caption);
		uploadForm.appendChild(input_path);
		uploadForm.appendChild(input_file);
		uploadForm.appendChild(img_container);
		document.body.parentNode.appendChild(iframe);
		
		uploadForm.appendChild(aOK);
		uploadForm.appendChild(aCancel);
		
		
		uploadForm.input_file = input_file;
		uploadForm.img_container = img_container;
		uploadForm.iframe = iframe;
		
		document.body.appendChild(uploadForm);
		
		z.addClass(uploadForm, 'box');
		
	}
	//z.s('upload_img').width = '';
	if (src)
		z.s('upload_img').src = src;
	uploadForm.style.display = 'block';
};

/*setInterval (function () {
    z.loop();
}, z.interval);*/
z._init();

})();
